#include "Mouse/Mouse.hpp"

// 鼠标回调函数
void mouseCallback(int event, int x, int y, int flags, void *userdata);

Mouse::Mouse() :
    rclcpp ::Node("Mouse")
{
    RCLCPP_INFO(this->get_logger(), "Xu_Hua : Mouse生成 !!!");
    Timer_01 = create_wall_timer(std::chrono::milliseconds(33), std::bind(&Mouse::Timer_Callback_01, this));
    // Pub_ = this->create_publisher<message_interface_ice::msg::Mouse>("~/Pub_Topic", 5);
    // Sub_ = this->create_subscription<message_interface_ice::msg::Mouse>("~/Pub_Topic", 5, std::bind(&Mouse::Sub_Callback, this, std::placeholders::_1));
    // 初始化视频捕获
    cap.open(0); // 打开默认摄像头
    if (!cap.isOpened())
    {
        RCLCPP_ERROR(this->get_logger(), "无法打开摄像头！");
        return;
    }

    // 创建窗口并设置鼠标回调
    cv::namedWindow("Image", cv::WINDOW_AUTOSIZE);
    cv::setMouseCallback("Image", mouseCallback, NULL);
}

void Mouse::Timer_Callback_01()
{
    // cv::Mat frame;
    if (cap.read(frame))
    {
        cv::circle(frame, cv::Point(g_u, g_v), 3, cv::Scalar(0, 255, 0), -1);
        // 显示视频帧
        cv::imshow("Image", frame);
        cv::waitKey(1); // 等待1毫秒
    } else
    {
        RCLCPP_ERROR(this->get_logger(), "无法读取视频帧！");
    }
}
// 鼠标回调函数
void mouseCallback(int event, int x, int y, int flags, void *userdata)
{
    // 简单使用参数以消除警告
    (void)flags; // 告诉编译器忽略未使用警告
    (void)userdata;
#ifdef MOUSE_HOVER_MODE
    // 鼠标悬停模式：鼠标移动时更新坐标
    if (event == cv::EVENT_MOUSEMOVE)
    {
        g_u = x;
        g_v = y;
        std::cout << "鼠标悬停位置: (" << g_u << ", " << g_v << ")" << std::endl;
    }
#endif

#ifdef MOUSE_CLICK_MODE
    // 鼠标点击模式：左键点击时更新坐标
    if (event == cv::EVENT_LBUTTONDOWN)
    {
        g_u = x;
        g_v = y;
        std::cout << "鼠标点击位置: (" << g_u << ", " << g_v << ")" << std::endl;
    }
#endif
}
int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);
    auto node = std::make_shared<Mouse>();
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}
